package jndi.ldap.biz;

import jndi.ldap.LdapConnection;
import jndi.ldap.LdapEnv;
import jndi.ldap.domains.LdapUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : Roy.Yang
 *         Date: 1/20/12
 */
public class DefaultLdapOperator implements LdapOperator {
    private final static Logger log = LoggerFactory.getLogger(DefaultLdapOperator.class);

    /**
     * all operations would based on this connection.
     */
    private LdapConnection connection;

    public List<SearchResult> search(String searchFilter, SearchControls cons) {
        List<SearchResult> results = new ArrayList<SearchResult>();
        List<String> defaultBaseDNs = LdapEnv.getDefaultBaseDNs();
        for (String baseDN : defaultBaseDNs) {
            List<SearchResult> portion = search(baseDN, searchFilter, cons);
            results.addAll(portion);
        }

        return results;
    }

    public List<SearchResult> search(String searchBase, String searchFilter, SearchControls cons) {
        List<SearchResult> results = new ArrayList<SearchResult>();

        try {
            NamingEnumeration<SearchResult> enumResults = connection.search(searchBase, searchFilter, cons);
            while (enumResults.hasMoreElements()) {
                results.add(enumResults.nextElement());
            }
        } catch (NamingException e) {
            throw new RuntimeException(e);
        }

        return results;
    }

    public LdapUser findUser(String username) {
        return null;
    }

    public List<? extends LdapUser> findUsers(String usernameFilter) {
        return null;
    }

    public SearchResult getRootDSE() {
        return null;
    }

    public LdapConnection getConnection() {
        return this.connection;
    }

    public void setConnection(LdapConnection connection) {
        this.connection = connection;
    }
}
